import { weChatTimeFormat } from "@/utils/common";
import store from "@/store/index";
import { throttle, debounce } from "@/utils/util.js";
import { personFriendInfo } from "@/services/makeFriend";
import {
  queryModuleGroupList,
  queryCreateModuleGroup,
  queryGroupDetail,
} from "@/services/group";
import { customerUserAssign } from "@/services/customer.js";
import { mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      systemLocale: "",
      applicationLocale: "",
      femalePic: "http://www.omlook.com/imol/default_female.png",
      malePic: "http://www.omlook.com/imol/default_male.png",
    };
  },
  computed: {
    mycountryList() {
      return store.state.countryList;
    },
    locales() {
      return [
        // {
        // 		text: this.$t('locale.auto'),
        // 		code: 'auto'
        // 	},
        {
          // text: this.$t("locale.en"),
          text: "English",
          code: "en",
        },
        {
          // text: this.$t("locale.ru"),
          text: "Русский",
          code: "ru",
        },
        {
          // text: this.$t("locale.zh-hans"),
          text: "简体中文",
          code: "zh-Hans",
        },
      ];
    },
    localesValue() {
      const arr = this.locales.filter(
        (item) => item.code == this.applicationLocale
      );
      if (!arr?.length) {
        return this.systemLocale;
      } else {
        return arr[0].text;
      }
    },
    localesCode() {
      const arr = this.locales.filter(
        (item) => item.code == this.applicationLocale
      );
      if (!arr?.length) {
        return this.systemLocale;
      } else {
        return arr[0].code;
      }
    },
    avatorIsShow() {
      let list = this.fillterMessages;
      let userId = store.state.userId;
      if (list.length > 0) {
        list.map((item) => {
          item.showAvatorNow = true;
          return item;
        });
        let newList = list.filter((item) => {
          return (
            (item.messageType != "OL:ReadStatus" &&
              item.messageType != "RC:RcCmd" &&
              item.messageType !== "OL:Prerender") ||
            (item.messageType === "OL:Prerender" &&
              item.senderUserId === userId)
          );
        });
        newList.map((item, index) => {
          if (index > 0) {
            if (
              userId !== item.senderUserId &&
              userId !== newList[index - 1].senderUserId &&
              item.senderUserId == newList[index - 1].senderUserId &&
              weChatTimeFormat(item.sentTime) ==
                weChatTimeFormat(newList[index - 1].sentTime)
            ) {
              list.map((e) => {
                if (e.messageId === item.messageId) {
                  e.showAvatorNow = false;
                }
                return e;
              });
            }
          }
        });
      }
      console.log("群聊聊天记录", list);
      return list;
    },
  },
  onLoad(option) {
    // if (uni.getLocale() == 'en') {
    // 	uni.setLocale('ru');
    // 	this.$i18n.locale = 'ru';
    // }
    let systemInfo = uni.getSystemInfoSync();
    this.systemLocale = systemInfo.language;
    this.applicationLocale = uni.getLocale();
    this.isAndroid = systemInfo.platform.toLowerCase() === "android";
    uni.onLocaleChange((e) => {
      this.applicationLocale = e.locale;
    });
    console.log("nnnnn", this.applicationLocale);
  },
  methods: {
    ...mapActions(["changeGroupList"]),
    // 跳转至用户协议
    gotoUserGreen() {
      uni.navigateTo({
        url: "/pages/user/AboutDetailUser",
      });
    },
    changeAvatarPic(obj) {
      if (obj.avatar == this.femalePic || obj.avatar == this.malePic) {
        obj.avatar = Number(obj.gender) == 1 ? this.malePic : this.femalePic;
        obj.avatarCompress = obj.avatar;
      }
      return obj;
    },
    // app中打开网页的方式
    setLinkTextOpenToHtml(msg) {
      let newMsg = msg;
      if (this.$store.state.isWebview) {
        const urlRegex =
          /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
        var matches = msg.match(urlRegex);
        if (matches && matches.length > 0) {
          matches.map((item) => {
            const newUrl = `<span onclick="window.open('${item}')" class="a-link">${item}</span>`;
            const setUrl = `<span onclick="javascript:olImInterface.navigateTo(${"`"}{'type':1005,'url':'${item}'}${"`"})" class="a-link">${item}</span>`;
            if (newMsg.indexOf(newUrl) >= 0) {
              newMsg = newMsg.replace(newUrl, setUrl);
            }
          });
        }
      }
      return newMsg;
    },
    hideBottomTabBar() {
      uni.hideTabBar({
        animation: false,
        success() {
          console.log("hide success");
        },
        fail() {
          console.log("hide error");
        },
      });
    },
    setTabBar() {
      if (
        typeof this.$mp.page.getTabBar === "function" &&
        this.$mp.page.getTabBar()
      ) {
        this.$mp.page.getTabBar().init();
      }
    },
    onLocaleChange(value) {
      uni.setLocale(value);
      this.$i18n.locale = value;
    },
    formatUserName(item) {
      let userName = "";
      if ((item.commentLast ?? "") || (item.commentName ?? "")) {
        if (item.commentName ?? "") {
          userName += item.commentName + " ";
        }
        if (item.commentLast ?? "") {
          userName += item.commentLast;
        }
      } else if (
        item.userVo &&
        ((item.userVo.commentName ?? "") || (item.userVo.commentLast ?? ""))
      ) {
        if (item.userVo.commentName ?? "") {
          userName += item.userVo.commentName + " ";
        }
        if (item.userVo.commentLast ?? "") {
          userName += item.userVo.commentLast;
        }
      } else if ((item.lastName ?? "") || (item.firstName ?? "")) {
        if (item.firstName ?? "") {
          userName += item.firstName + " ";
        }
        if (item.lastName ?? "") {
          userName += item.lastName;
        }
      } else if (
        item.userVo &&
        ((item.userVo.firstName ?? "") || (item.userVo.lastName ?? ""))
      ) {
        if (item.userVo.firstName ?? "") {
          userName += item.userVo.firstName + " ";
        }
        if (item.userVo.lastName ?? "") {
          userName += item.userVo.lastName;
        }
      } else {
        userName = item.userName;
      }
      return userName || "";
    },
    showLastMessages(item) {
      try {
        let msg = "";
        switch (item.latestMessage.messageType) {
          case "RC:ImgMsg":
            msg = "[photo]";
            break;
          case "RC:TxtMsg":
            msg = item.latestMessage.content.content;
            break;
          case "RC:SightMsg":
            msg = "[video]";
            break;
          case "RC:FileMsg":
            msg = "[file] " + item.latestMessage.content.name;
            break;
          case "OL:Recall":
            msg = item.latestMessage.content.content;
            break;
          case "OL:Card":
            msg = "[card]";
            break;
          case "OL:ReadStatus":
            msg = this.showLastMessages(item.latestMessage.content.preMsg);
            break;
          case "RC:RcCmd":
            msg = this.showLastMessages(item.latestMessage.content.extra);
            break;
          case "RC:HQVCMsg":
            msg = "[voice]";
            break;
          case "OL:VoiceMsg":
            if (item.latestMessage.content.mediaType == 1) {
              msg =
                ' <i class="iconfont icon-B" style="color: #878787;margin-right: 7px;"></i>';
            } else {
              msg =
                ' <i class="iconfont icon-shipintonghua1" style="color: #878787;margin-right: 7px;"></i>';
            }

            msg =
              msg +
              this.getCalledContent(
                item.latestMessage.content.endReason,
                item.latestMessage.content.duration
              );
            break;
          case "OL:Prerender":
            if (
              item.latestMessage.content.info.type === "img" ||
              item.latestMessage.content.info.type === "video"
            ) {
              msg =
                item.latestMessage.content.info.type === "img"
                  ? "[photo]" +
                    (item.latestMessage.expansion &&
                    item.latestMessage.expansion.content
                      ? " " + item.latestMessage.expansion.content
                      : "")
                  : "[video]" +
                    (item.latestMessage.expansion &&
                    item.latestMessage.expansion.content
                      ? " " + item.latestMessage.expansion.content
                      : "");
            } else {
              msg =
                "[file] " +
                item.latestMessage.content.info.name +
                (item.latestMessage.expansion &&
                item.latestMessage.expansion.content
                  ? " " + item.latestMessage.expansion.content
                  : "");
            }
            break;
          case "OL:WorkTickets":
            msg =
              `${this.$t("customerObj.Recording")}: ` +
              item.latestMessage.content.info.name;
            break;
          case "s:exchangeCard":
            msg = `${this.$t("recharge_withdrawal")}`;
            break;
          default:
            break;
        }
        return msg;
      } catch (error) {
        return "";
      }
    },
    // 返回通话状态显示的文字
    getCalledContent(endReason, duration) {
      let str = "";
      switch (endReason) {
        case 5:
        case 15:
          str = this.$t("chat.No-answer");
          break;
        case 13:
        case 3:
          str = this.$t("chat.Call-time") + duration;
          break;
        case 1:
        case 11:
          str = this.$t("chat.Canceled-back");
          break;
        case 12:
        case 2:
          str = this.$t("chat.rejected");
          break;
        case 22:
        case 32:
          str = this.$t("chat.The-other-party-has-declined");
          break;
        default:
          str = this.$t("chat.Unknown-cause");
          break;
      }
      return str;
    },
    // avatorIsShow (arr) {
    //   let list = arr
    //   let userId = store.state.userId
    //   if (list.length > 0) {
    //     list.map(item => {
    //       item.showAvatorNow = true
    //       return item
    //     })
    //     let newList = list.filter(item => {
    //       return item.messageType != 'OL:ReadStatus' && item.messageType != 'RC:RcCmd'
    //     })
    //     newList.map((item, index) => {
    //       if (index > 0) {
    //         if (userId !== item.senderUserId && userId !== newList[index - 1].senderUserId && item.senderUserId == newList[index - 1].senderUserId && weChatTimeFormat(item.sentTime) == weChatTimeFormat(newList[index - 1].sentTime)) {
    //           list.map(e => {
    //             if (e.messageId === item.messageId) {
    //               e.showAvatorNow = false
    //             }
    //             return e
    //           })
    //         }
    //       }
    //     })
    //   }
    // 	console.log('群聊聊天记录',list);
    //   return list
    // },
    multiSort(array, ...compairers) {
      return array.sort((a, b) => {
        for (const c of compairers) {
          const r = c(a, b);
          if (r !== 0) {
            return r;
          }
        }
      });
    },
    pySegSort(arr) {
      if (arr.length == 0) return;
      if (!String.prototype.localeCompare) return null;
      var letters = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
      var zh = "阿八嚓哒妸发旮哈哈讥咔垃痳拏噢妑七呥扨它它它穵夕丫帀".split("");
      var segs = []; // 存放数据
      var res = {};
      let curr;
      var re = /[^\u4e00-\u9fa5]/; //中文正则
      var pattern = new RegExp(
        "[`\\-~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？12345678990]"
      ); //特殊符号

      letters.filter((items, i) => {
        curr = {
          initial: "", //字母
          data: [], //数据
        };
        arr.map((v, index) => {
          // 特殊字符
          if (pattern.test(v.formatUserName[0])) {
            if (
              (!zh[i - 1] || zh[i - 1].localeCompare(v.formatUserName) <= 0) &&
              v.formatUserName.localeCompare(zh[i]) == -1
            ) {
              curr.data.push(v);
            }
          }
          // 判断首个字是否是中文
          if (re.test(v.formatUserName[0])) {
            // 英文
            if (v.formatUserName[0].toUpperCase() == items) {
              curr.data.push(v);
            }
          } else {
            // 中文
            if (
              (!zh[i - 1] || zh[i - 1].localeCompare(v.formatUserName) <= 0) &&
              v.formatUserName.localeCompare(zh[i]) == -1
            ) {
              curr.data.push(v);
            }
          }
        });

        if (curr.data.length) {
          curr.initial = letters[i];
          segs.push(curr);
          curr.data.sort((a, b) => {
            return a.formatUserName.localeCompare(b.formatUserName);
          });
        }
      });
      res.segs = Array.from(new Set(segs)); //去重
      console.log(res);
      let newArr = res.segs.filter((e) => {
        return e.initial !== "#";
      });
      let initialArr = res.segs.filter((e) => {
        return e.initial == "#";
      });
      newArr = [...newArr, ...initialArr];
      return newArr;
    },
    setTyping: debounce((event) => {
      event(false);
    }, 1000),
    // 发送自己再输入中的状态消息
    _sendTypingStatusMessage: throttle(function () {
      this.$RongIMLib.sendTypingStatusMessage(
        {
          conversationType: this.groupId ? 3 : 1,
          targetId: this.targetId || this.groupId,
        },
        this.$RongIMLib.MessageType.TEXT
      );
    }, 600),
    getRegionNameList(obj) {
      if (!obj) {
        return [];
      }
      if (this.language === "zh-Hans") {
        return [obj.parentInfo.cn, obj.childInfo.cn];
      } else if (this.language === "en") {
        return [obj.parentInfo.en, obj.childInfo.en];
      } else if (this.language === "ru") {
        return [obj.parentInfo.ru, obj.childInfo.ru];
      } else {
        return [];
      }
    },
    getCountryName(obj) {
      if (!obj) {
        return "";
      }
      if (this.language === "zh-Hans") {
        return obj.cn;
      } else if (this.language === "en") {
        return obj.en;
      } else if (this.language === "ru") {
        return obj.ru;
      } else {
        return "";
      }
    },
    // 查是否发布过交友资料
    async handleReleaseInfoGlobal() {
      if (this.$store.state.token) {
        const resp = await personFriendInfo({
          userId: this.$store.state.userInfo.userId,
        });
        if (!resp.success) return;
        var aleardyEdit = this.changeAvatarPic(resp.result.data);
        // if (aleardyEdit.userPersonalsId) {
        this.$store.state.friendsInformation = aleardyEdit;
        // }
      }
    },
    //获取其他群组信息
    async getModuleGroupList() {
      if (this.$store.state.token) {
        const resp = await queryModuleGroupList();
        if (!resp.success) return;
        const { data } = resp.result;
        data.forEach((t) => {
          var info = this.$store.state.moduleGroupInfo[t.moduleType];
          if (info && Array.isArray(info)) {
            let obj = info.find((o) => o.groupId == t.groupId);
            if (!obj) info.push(t);
          } else {
            this.$store.state.moduleGroupInfo[t.moduleType] = [t];
          }
        });
      }
    },
    // 导航栏左侧返回按钮 <=
    leftClick(urlIndex) {
      let localName = urlIndex ? `prePagesUrl-${urlIndex}` : "prePagesUrl";
      if (getCurrentPages().length > 1) {
        uni.navigateBack({
          delta: 1,
        });
      } else {
        uni.redirectTo({
          url: `/${uni.getStorageSync(localName)}`,
          fail: () => {
            uni.switchTab({
              url: `/${uni.getStorageSync(localName)}`,
            });
          },
        });
      }
      uni.removeStorageSync(localName);
    },
    // 获取上一个页面的路径已经参数
    getPrePages(urlIndex) {
      if (getCurrentPages().length <= 1) return;
      let pages = getCurrentPages(); // 获取页面栈
      let path = pages[pages.length - 2].route; // 获取上一个页面的url
      let options = pages[pages.length - 2].options; // 获取上一个页面的url参数
      let url = this.jointUrl(path, options); // 拼接路径参数
      let localName = urlIndex ? `prePagesUrl-${urlIndex}` : "prePagesUrl";
      uni.setStorageSync(localName, url); // 将路径存在本地
    },
    // 拼接路径参数
    jointUrl(path, options) {
      let url = path + "?";
      for (const key in options) {
        const value = options[key];
        url += key + "=" + value + "&";
      }
      url = url.substring(0, url.length - 1);
      return url;
    },
    isPeopleAvatarExit(avatar) {
      return (
        avatar &&
        avatar != "https://dh.yihaidata.com/imol/account.png" &&
        avatar != "http://www.omlook.com/imol/account.png"
      );
    },
    // 分配客服
    // 1OTC交易，2场内交易，3红包，4转账，5交友，6招聘，7悬赏，8信息
    async getCustomer(moduleType, selected) {
      if (!this.$store.state.token) {
        uni.navigateTo({
          url: "/pages/login/Login",
        });
        return;
      }
      uni.showLoading();
      const resp = await customerUserAssign({
        moduleType: moduleType,
      });
      const code = resp.result.code;
      const data = resp.result.data;
      if (code === 200 && data) {
        this.chatWithCustomer(data, moduleType, selected);
      }
    },
    async chatWithCustomer(customer, moduleType, selected) {
      uni.showLoading();
      var { result } = await queryCreateModuleGroup({
        groupName: customer.imNickName,
        avatar: this.$store.state.normalPic,
        avatarCompress: this.$store.state.normalPic,
        memberIds: [customer.imUserId],
        moduleType: 6,
        responsibleModule: moduleType,
      });
      if (result.code === 200) {
        uni.showLoading();
        var group = await this.$RongIMLib.getConversation({
          targetId: result.data,
          conversationType: 3,
        });
        const resp = await queryGroupDetail(result.data);
        uni.showLoading();
        if (resp.success) {
          resp.result.data.myName = resp.result.data.jyRemark || "OMLOOKER";
          if (group) {
            group.data.info = resp.result.data;
            var groupList = this.$store.state.groupList;
            if (!this.$store.state.moduleGroupInfo[6]) {
              this.$store.state.moduleGroupInfo[6] = [
                {
                  groupId: result.data,
                  groupName: customer.imNickName,
                  moduleType: 6,
                },
              ];
            } else {
              var index = this.$store.state.moduleGroupInfo[6].find(
                (o) => o.groupId == result.data
              );
              if (index == -1) {
                this.$store.state.moduleGroupInfo[6].push({
                  groupId: result.data,
                  groupName: customer.imNickName,
                  moduleType: 6,
                });
              }
            }
            var gIndex = groupList.indexOf((o) => o.groupId == result.data);
            if (gIndex > -1) {
              groupList[gIndex] = group.data.info;
            } else {
              groupList.push(group.data.info);
            }
            await this.changeGroupList(groupList);
            console.log(this.$store.state.groupList);
            uni.setStorageSync("needSelectCustomer", JSON.stringify(selected));
            uni.hideLoading();
            //直接跳转页面
            uni.navigateTo({
              url:
                "/pages/chat/GroupChat?isFriendGroup=true&backType=1&isModule=true&groupId=" +
                result.data,
              fail(err) {
                console.log(err);
                uni.hideLoading();
              },
            });
          }
        }
      }
    },
  },
};
